#include <QtGui>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "tabwidget.h"
#include "usersetting.h"

const static int STATUS_BAR_TIMEOUT = 5000; // in millisecond
const static QString WINDOW_TITLE_TEMPLATE = QObject::tr("Qt Messenger Demo - [%1]");

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    mUi(new Ui::MainWindow),
    mSetting(new UserSetting)
{
    mUi->setupUi(this);

    // Tab Widget
    mTabWidget = new TabWidget();
    mUi->centralLayout->addWidget(mTabWidget);
    connect(mTabWidget, SIGNAL(sendMessage(const QString &, const QString &)),
            this, SIGNAL(sendMessage(const QString &, const QString &)));
    connect(mTabWidget, SIGNAL(stopChating(QString)),
            this, SIGNAL(stopChating(QString)));

    // Menu
    createMenus();
}

MainWindow::~MainWindow()
{
    delete mSetting;
    delete mUi;
}

void MainWindow::login()
{
    QString username = mSetting->getUserName();
    if (username.isEmpty())
    {
        getUserNameFromDialog(username);
    }

    mSetting->setUserName(username);
    onUserNameUpdated(username);
    emit login(username);
}

void MainWindow::closeEvent(QCloseEvent * event)
{
    emit closeWindow();
}

void MainWindow::createMenus()
{
    QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
    QAction *exitAction = new QAction(tr("&Exit"), this);
    fileMenu->addAction(exitAction);
    connect(exitAction, SIGNAL(triggered()),
            this, SLOT(close()));

    QMenu *optionMenu = menuBar()->addMenu(tr("&Option"));
    QAction *settingAction = new QAction(tr("&Setting"), this);
    optionMenu->addAction(settingAction);
    connect(settingAction, SIGNAL(triggered()),
            this, SLOT(onSettingAction()));

    QMenu *helpMenu = menuBar()->addMenu(tr("&Help"));
    QAction *aboutAction = new QAction(tr("&About"), this);
    helpMenu->addAction(aboutAction);
    connect(aboutAction, SIGNAL(triggered()),
            this, SLOT(onAboutAction()));

	// [For Test]
    //createTestMenu();
}

void MainWindow::createTestMenu()
{
    QMenu *uiTestMenu = menuBar()->addMenu(tr("Test"));

    QAction *testLoginAction = new QAction(tr("Test Login Result"), this);
    uiTestMenu->addAction(testLoginAction);
    connect(testLoginAction, SIGNAL(triggered()),
            this, SLOT(testLoginResultReceived()));

    QAction *testNetworkStatusAction = new QAction(tr("Test Network Status"), this);
    uiTestMenu->addAction(testNetworkStatusAction);
    connect(testNetworkStatusAction, SIGNAL(triggered()),
            this, SLOT(testNetworkStatusChanged()));

    QAction *testMessageReceivedAction = new QAction(tr("Test Message Received"), this);
    uiTestMenu->addAction(testMessageReceivedAction);
    connect(testMessageReceivedAction, SIGNAL(triggered()),
            this, SLOT(testMessageUpdated()));

    QAction *testContactListAction = new QAction(tr("Test Contact List Updated"), this);
    uiTestMenu->addAction(testContactListAction);
    connect(testContactListAction, SIGNAL(triggered()),
            this, SLOT(testContactListUpdated()));

    QAction *testUserNameAction = new QAction(tr("Test User Name Updated"), this);
    uiTestMenu->addAction(testUserNameAction);
    connect(testUserNameAction, SIGNAL(triggered()),
            this, SLOT(testUserNameUpdated()));

}

void MainWindow::onAboutAction()
{
    QMessageBox::about(this, tr("About Qt Messenger Demo"),
            tr("<h2>Qt Messenger Demo 1.0</h2>"
               "<p>Contact us:<br/>"
               "mingjin.wu@gmail.com<br/>"
               "sinis@tom.com<br/>"
               "zhangjimin795@gmail.com</p>"));
}

void MainWindow::onSettingAction()
{
    QString username;
    if (getUserNameFromDialog(username))
    {
        mSetting->setUserName(username);
        onUserNameUpdated(username);
        emit login(username);
    }
}

void MainWindow::onNetworkStatusChanged(eNetworkStatus networkStatus)
{
    if (0 <= networkStatus &&  networkStatus < networkStatusEnd)
    {
        statusBar()->showMessage(networkStatusDescription[networkStatus], STATUS_BAR_TIMEOUT);
    }
}

void MainWindow::onLoginResultReceived(eLoginStatus loginStatus)
{
    if (0 <= loginStatus && loginStatus < loginStatusEnd)
    {
        statusBar()->showMessage(loginStatusDescription[loginStatus], STATUS_BAR_TIMEOUT);
    }
}

void MainWindow::onContactListUpdated(const QList<userInfo> &contactList)
{
    mTabWidget->updateContactList(contactList);
    update();
}

void MainWindow::onMessageUpdated(const QString &ip, const QList<recordInfo> &messageList)
{
    mTabWidget->updateMessage(ip, messageList);
    update();
}

void MainWindow::onUserNameUpdated(const QString &userName)
{
    mUserName = userName;
    setWindowTitle(WINDOW_TITLE_TEMPLATE.arg(userName));
}

void MainWindow::testNetworkStatusChanged()
{
    onNetworkStatusChanged(networkError);
}

void MainWindow::testLoginResultReceived()
{
    onLoginResultReceived(loginSuccessful);
}

void MainWindow::testContactListUpdated()
{
    QList<userInfo> list;
    userInfo info;
    info.setIp("127.0.0.1");
    info.setName("Alice");
    list.append(info);

    info.setIp("127.0.0.2");
    info.setName("Bob");
    list.append(info);

    onContactListUpdated(list);
}

void MainWindow::testMessageUpdated()
{
    QList<recordInfo> list;
    for (int index = 0; index < 50; ++index)
    {
        recordInfo info;
        info.setErrorCode(0);
        info.setName((index%2)?"Alice":"Bob");
        info.setContent("hello hello hello hello hello hello hello hello world world!!! \
                        hello hello hello hello hello hello hello hello world world!!!");
        list.append(info);
    }

    onMessageUpdated(QString("127.0.0.1"), list);
}

void MainWindow::testUserNameUpdated()
{
    onUserNameUpdated("Tencent");
}

bool MainWindow::getUserNameFromDialog(QString &newUserName)
{
    bool ok;
    QString text = QInputDialog::getText(this,
                                         tr("User Name"),
                                         tr("Please input your user name:"),
                                         QLineEdit::Normal,
                                         mUserName,
                                         &ok);
    if (ok)
    {
        newUserName = text;
        return true;
    }

    return false;
}
